package com.cn.wanxi.servlet.back.product;

//import com.cn.wanxi.util.Upload;

import com.cn.wanxi.model.ProductModel;
import com.cn.wanxi.model.ResultModel;
import com.cn.wanxi.service.IproductService;
import com.cn.wanxi.service.impl.ProductServiceImpl;
import com.cn.wanxi.util.Tool;
import com.cn.wanxi.util.Upload;
import net.sf.json.JSONArray;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@WebServlet("/productAdd")
public class ProductAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Upload upload = new Upload();
        String string = upload.fileImg(req);
        ProductModel productModel = new ProductModel();
        String aa[] = string.split("@@");
        productModel.setCuisineId(Integer.parseInt(aa[0]));
        productModel.setTitle(aa[1]);
        String price = aa[2];
        price = "".equals(price) || price == null ? "0" : price;
        productModel.setPrice(Double.parseDouble(price));
        productModel.setContent(aa[3]);
        productModel.setImgHref(aa[4]);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
        String ct = simpleDateFormat.format(new Date());//将时间转换成所需要的格式
        productModel.setCreateTime(ct);


        IproductService iproductService = new ProductServiceImpl();
        ResultModel resultModel = new ResultModel();
        String ids = req.getParameter("productId");
        Integer id = ids == null || "".equals(ids) ? 0 : Integer.parseInt(ids);
        //判断id，如果有则为编辑，否则为修改
        if (id != 0) {
            productModel.setId(id);
            resultModel = iproductService.update(productModel);
        } else {
            resultModel = iproductService.add(productModel);
        }

        JSONArray jsonArray = JSONArray.fromObject(resultModel);
        resp.getWriter().println(jsonArray);

    }
}
